/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package banksystem;

import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author ROBM
 */
public class CDTransferFrame extends javax.swing.JFrame {

	Controller mController;
	Account mAccount1;
	Account mAccount2;
	CertificateOfDeposit mCD1;
	CertificateOfDeposit mCD2;
	boolean withdraw = false;
	Timer mRefreshTimer = null;
	
	/**
	 * Creates new form TransferFrame
	 */
	public CDTransferFrame(Controller controller, Account account1, Account account2) {
		initComponents();
		
		mAccount1 = account1;
		mAccount2 = account2;
		
		if(account1.getClass().equals(CertificateOfDeposit.class)) {
			withdraw = true;
			mCD1 = (CertificateOfDeposit) account1;
		} else {
			mCD2 = (CertificateOfDeposit) account2;
		}
		
		mController = controller;
	
		if(withdraw) {
			if(mCD1.isMatured()) {
				this.TransferLabel.setText("Close CD");
				this.transferAmountTextField.setText(Double.toString(mCD1.getBalance()));
				this.transferAmountTextField.setEditable(false);
			} else {
				this.TransferLabel.setText("Withdraw From CD");
			}
			mRefreshTimer = new Timer();
			mRefreshTimer.scheduleAtFixedRate(new RefreshClass(), 1000, 1000);
		}
		
		
		this.account1Label.setText(this.account1Label.getText() + this.mAccount1.getName());
		this.account2Label.setText(this.account2Label.getText() + this.mAccount2.getName());
		
		this.balanceLabel1.setText("$" + Double.toString(mAccount1.getBalance()));
		this.balanceLabel2.setText("$" + Double.toString(mAccount2.getBalance()));
		
		this.errorLabel.setVisible(false);
	}

	private void refresh() {
		if(withdraw) {
			if(mCD1.isMatured()) {
				this.TransferLabel.setText("Close CD");
				this.transferAmountTextField.setText(Double.toString(mCD1.getBalance()));
				this.transferAmountTextField.setEditable(false);
			} else {
				this.TransferLabel.setText("Withdraw From CD");
			}
		}
			
		this.balanceLabel1.setText("$" + Double.toString(mAccount1.getBalance()));
		this.balanceLabel2.setText("$" + Double.toString(mAccount2.getBalance()));
	}
	
	class RefreshClass extends TimerTask {
		@Override
		public void run() {
			refresh();
		}
	}
	
	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        TransferLabel = new javax.swing.JLabel();
        balanceLabel1 = new javax.swing.JLabel();
        balanceLabel2 = new javax.swing.JLabel();
        account1Label = new javax.swing.JLabel();
        account2Label = new javax.swing.JLabel();
        ammountLabel = new javax.swing.JLabel();
        transferAmountTextField = new javax.swing.JTextField();
        submitButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        errorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        TransferLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        TransferLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        TransferLabel.setLabelFor(this);
        TransferLabel.setText("Transfer");

        balanceLabel1.setText("Balance: ");

        balanceLabel2.setText("Balance:");

        account1Label.setText("From: ");

        account2Label.setText("To: ");

        ammountLabel.setText("Amount:");

        submitButton.setText("Submit");
        submitButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                submitButtonMouseClicked(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });

        errorLabel.setForeground(new java.awt.Color(204, 0, 0));
        errorLabel.setText("Error: ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(submitButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(cancelButton)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(TransferLabel)
                .addGap(200, 200, 200))
            .addGroup(layout.createSequentialGroup()
                .addGap(77, 77, 77)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(errorLabel)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(balanceLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(balanceLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(account2Label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(account1Label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(ammountLabel)
                                    .addComponent(transferAmountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 47, Short.MAX_VALUE)))
                        .addGap(183, 183, 183))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TransferLabel)
                .addGap(9, 9, 9)
                .addComponent(account1Label)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(balanceLabel1)
                .addGap(18, 18, 18)
                .addComponent(account2Label)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(balanceLabel2)
                .addGap(18, 18, 18)
                .addComponent(ammountLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(transferAmountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(errorLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(submitButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void submitButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_submitButtonMouseClicked
		String text;
		double amount;
		double testAmount;
		
		try{
			text = this.transferAmountTextField.getText();
			try{
				amount = currencyToDouble(text);
				testAmount = amount;
				if(withdraw) { //if it's a withdraw
					if(!mCD1.isMatured()) { //if the cd is not matured
						testAmount = amount + mCD1.getPenaltyAmount(amount);
					} else {
						amount = mCD1.getBalance();
					}
				}
				if( testAmount <= this.mAccount1.getBalance())
				{
					this.mController.TransferBetweenAccounts(amount);
				}else{
					if(withdraw) { 
						errorLabel.setText("Error: Amount Exceeds Avaliable Balance and " + mCD1.getPenaltyAmount(amount) + " penalty");
					} else {
						errorLabel.setText("Error: Amount Exceeds Avaliable Balance");
					}
					errorLabel.setVisible(true);
					this.refresh();
				}	
			}catch(NumberFormatException e){
				errorLabel.setText("Error: Please Enter A Valid Number");
				errorLabel.setVisible(true);
				this.refresh();
			}	
		}catch(NullPointerException e){
			errorLabel.setText("Error: Please Enter A Number");
			errorLabel.setVisible(true);
			this.refresh();
		}
	}//GEN-LAST:event_submitButtonMouseClicked

	private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseClicked
		this.mController.SaveAndRestart(this);
	}//GEN-LAST:event_cancelButtonMouseClicked

	/**
	 * Converts a string representing US currency into a double
	 * 
	 * @param str a string representing currency
	 * @return A double equivalent to the str
	 * @throws NumberFormatException
	 * @throws NullPointerException 
	 */
	private double currencyToDouble(String str) 
			throws NumberFormatException, NullPointerException
	{
		double num;
		
		if(str.matches("\\$?[0-9]*\\.?[0-9]{0,2}"))
		{
			str = str.replaceFirst("[$]", "");
			num = Double.valueOf(str);
		}else{
			throw new NumberFormatException("Invalid Currency");
		}
		
		return num;
	}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel TransferLabel;
    private javax.swing.JLabel account1Label;
    private javax.swing.JLabel account2Label;
    private javax.swing.JLabel ammountLabel;
    private javax.swing.JLabel balanceLabel1;
    private javax.swing.JLabel balanceLabel2;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JButton submitButton;
    private javax.swing.JTextField transferAmountTextField;
    // End of variables declaration//GEN-END:variables
}
